package com.king.config;

import cn.hutool.core.map.MapUtil;
import com.king.shiro.AccountRealm;
import com.king.shiro.AuthFilter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Configuration
public class ShiroConfig {

    @Bean
    public SecurityManager securityManager(AccountRealm accountRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(accountRealm);

        log.info("shiro SecurityManager --> 注入成功！");

        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);

        //配置登录的url和登录成功的url
        filterFactoryBean.setLoginUrl("/login");
        filterFactoryBean.setSuccessUrl("/");

        //配置未授权的跳转页面
        filterFactoryBean.setUnauthorizedUrl("/error/403");

        //配置自定义过滤器
        filterFactoryBean.setFilters(MapUtil.of("auth",authFilter()));

        //配置url是否需要权限
        Map<String,String> hashMap = new LinkedHashMap<>();
        /*hashMap.put("/user/home","authc");//需要
        hashMap.put("/user/set","authc");
        hashMap.put("/user/upload","authc");*/

        /*hashMap.put("/collection/add","authc");
        hashMap.put("/collection/remove","authc");
        hashMap.put("/collection/find","authc");*/

        /*hashMap.put("/login","anon");//不需要*/

        /*hashMap.put("/user/home","auth");//需要
        hashMap.put("/user/{id:\\d*}","auth");
        hashMap.put("/user/set","auth");
        hashMap.put("/user/upload","auth");
        hashMap.put("/user/index","auth");
        hashMap.put("/user/message","auth");*/

        hashMap.put("/user/**","auth");

        /*hashMap.put("/collection/add/","auth");
        hashMap.put("/collection/remove/","auth");
        hashMap.put("/collection/find/","auth");*/

        hashMap.put("/collection/**","auth");
        hashMap.put("/message/**","auth");

        hashMap.put("/post/edit","auth");
        hashMap.put("/post/submit","auth");
        hashMap.put("/post/delete","auth");
        hashMap.put("/post/reply","auth");


        hashMap.put("/**","anon");//不需要

        filterFactoryBean.setFilterChainDefinitionMap(hashMap);

        return filterFactoryBean;
    }

    @Bean
    AuthFilter authFilter() {
        return new AuthFilter();
    }
}
